package luj.groovy.excel.internal.table.header.path

import luj.groovy.excel.api.table.header.HeaderField

class HeaderByPathFinder {

  HeaderByPathFinder(List<HeaderField> fieldList, String path) {
    _fieldList = fieldList
    _path = path
  }

  HeaderField findByPath() {
    String[] parts = _path.split('/')
    return findImpl(_fieldList, parts, 0)
  }

  private HeaderField findImpl(List<HeaderField> list, String[] parts, int partIndex) {
    String name = parts[partIndex]
    def fieldO = list.stream()
        .filter { it.name == name }
        .findAny()

    if (!fieldO.isPresent()) {
      return null
    }

    HeaderField field = fieldO.get()
    int nextIndex = partIndex + 1
    if (nextIndex >= parts.length) {
      return field
    }

    return findImpl(field.getChildFields(), parts, nextIndex)
  }

  private final List<HeaderField> _fieldList

  private final String _path
}
